package com.example.aspect;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class MyAdvice {

    public static Logger logger = LoggerFactory.getLogger(MyAdvice.class);


    @Pointcut(value = "execution( * com.example.controller.*.*(..))")
    public void myPointcut(){
    }

    @Pointcut(value = "execution( * com.example.controller.*.*(..))")
    public void myPointcutBefore(){
    }

    @Pointcut(value = "execution( * com.example.controller.*.*(..))")
    public void myPointcutAfter(){
    }

    @Around("myPointcut()")
    public Object addLog(ProceedingJoinPoint joinPoint) throws Throwable {
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] argus = joinPoint.getArgs();
        ObjectMapper mapper = new ObjectMapper();
        logger.error("进入环绕通知，当前类名："+className+" 当前方法名："+methodName+"入参："+mapper.writeValueAsString(argus));
        Object object = joinPoint.proceed();
        logger.error("返回结果："+mapper.writeValueAsString(object));
        return object;
    }

    @Before("myPointcutAfter()")
    public void before(JoinPoint joinPoint) throws Throwable {
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] argus = joinPoint.getArgs();
        ObjectMapper mapper = new ObjectMapper();
        logger.error("进入到后置，通知，当前类名："+className+" 当前方法名："+methodName+"入参："+mapper.writeValueAsString(argus));
    }

    @After("myPointcutBefore()")
    public void after(JoinPoint joinPoint) throws Throwable {
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] argus = joinPoint.getArgs();
        ObjectMapper mapper = new ObjectMapper();
        logger.error("进入到后置通知，当前类名："+className+" 当前方法名："+methodName+"入参："+mapper.writeValueAsString(argus));
    }
}
